// 内容脚本，负责在网页中检测和提取资源

// 存储提取到的资源
let resources = {
  images: [],
  videos: [],
  audios: []
};

// 资源面板状态
let panelVisible = false;

// 创建资源面板
function createResourcePanel() {
  // 检查面板是否已存在
  if (document.getElementById('resource-extractor-panel')) {
    return;
  }

  // 创建面板容器
  const panel = document.createElement('div');
  panel.id = 'resource-extractor-panel';
  panel.className = 'resource-panel';
  panel.style.display = panelVisible ? 'block' : 'none';

  // 创建面板头部
  const header = document.createElement('div');
  header.className = 'panel-header';
  header.innerHTML = '<h3>网页资源提取器</h3>';

  // 创建关闭按钮
  const closeBtn = document.createElement('button');
  closeBtn.className = 'close-btn';
  closeBtn.innerHTML = '&times;';
  closeBtn.addEventListener('click', togglePanel);
  header.appendChild(closeBtn);

  // 创建面板内容
  const content = document.createElement('div');
  content.className = 'panel-content';

  // 创建标签页
  const tabs = document.createElement('div');
  tabs.className = 'tabs';
  tabs.innerHTML = `
    <button class="tab-btn active" data-tab="images">图片 (${resources.images.length})</button>
    <button class="tab-btn" data-tab="videos">视频 (${resources.videos.length})</button>
    <button class="tab-btn" data-tab="audios">音频 (${resources.audios.length})</button>
  `;

  // 创建标签页内容
  const tabContents = document.createElement('div');
  tabContents.className = 'tab-contents';

  // 创建图片标签页内容
  const imagesTab = document.createElement('div');
  imagesTab.className = 'tab-content active';
  imagesTab.id = 'images-tab';
  imagesTab.appendChild(createResourceList('images', resources.images));

  // 创建视频标签页内容
  const videosTab = document.createElement('div');
  videosTab.className = 'tab-content';
  videosTab.id = 'videos-tab';
  videosTab.appendChild(createResourceList('videos', resources.videos));

  // 创建音频标签页内容
  const audiosTab = document.createElement('div');
  audiosTab.className = 'tab-content';
  audiosTab.id = 'audios-tab';
  audiosTab.appendChild(createResourceList('audios', resources.audios));

  // 添加标签页内容到容器
  tabContents.appendChild(imagesTab);
  tabContents.appendChild(videosTab);
  tabContents.appendChild(audiosTab);

  // 添加标签页切换事件
  tabs.addEventListener('click', (e) => {
    if (e.target.classList.contains('tab-btn')) {
      // 移除所有活动状态
      document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
      document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));

      // 添加活动状态到点击的标签
      e.target.classList.add('active');
      const tabId = e.target.getAttribute('data-tab') + '-tab';
      document.getElementById(tabId).classList.add('active');
    }
  });

  // 组装面板
  content.appendChild(tabs);
  content.appendChild(tabContents);
  panel.appendChild(header);
  panel.appendChild(content);

  // 创建触发按钮
  const triggerBtn = document.createElement('div');
  triggerBtn.id = 'resource-extractor-trigger';
  triggerBtn.className = 'trigger-btn';
  triggerBtn.innerHTML = '<span>资源</span>';
  triggerBtn.addEventListener('click', togglePanel);

  // 添加到页面
  document.body.appendChild(panel);
  document.body.appendChild(triggerBtn);

  // 添加右键菜单事件
  document.addEventListener('contextmenu', handleContextMenu);
}

// 创建资源列表
function createResourceList(type, items) {
  const list = document.createElement('div');
  list.className = 'resource-list';

  if (items.length === 0) {
    const emptyMsg = document.createElement('p');
    emptyMsg.className = 'empty-message';
    emptyMsg.textContent = '没有找到资源';
    list.appendChild(emptyMsg);
    return list;
  }

  items.forEach((item, index) => {
    const resourceItem = document.createElement('div');
    resourceItem.className = 'resource-item';
    resourceItem.setAttribute('data-url', item.url);
    resourceItem.setAttribute('data-index', index);
    resourceItem.setAttribute('data-type', type);

    // 创建预览
    const preview = document.createElement('div');
    preview.className = 'resource-preview';

    if (type === 'images') {
      const img = document.createElement('img');
      img.src = item.url;
      img.alt = item.filename;
      preview.appendChild(img);
    } else if (type === 'videos') {
      preview.innerHTML = '<div class="video-icon">🎬</div>';
    } else if (type === 'audios') {
      preview.innerHTML = '<div class="audio-icon">🎵</div>';
    }

    // 创建信息
    const info = document.createElement('div');
    info.className = 'resource-info';
    info.innerHTML = `
      <div class="resource-name">${item.filename}</div>
      <div class="resource-size">${formatSize(item.size)}</div>
    `;

    // 创建下载按钮
    const downloadBtn = document.createElement('button');
    downloadBtn.className = 'download-btn';
    downloadBtn.innerHTML = '下载';
    downloadBtn.addEventListener('click', () => {
      downloadResource(item.url, item.filename);
    });

    // 组装资源项
    resourceItem.appendChild(preview);
    resourceItem.appendChild(info);
    resourceItem.appendChild(downloadBtn);
    list.appendChild(resourceItem);
  });

  return list;
}

// 格式化文件大小
function formatSize(bytes) {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 切换面板可见性
function togglePanel() {
  chrome.runtime.sendMessage({ action: 'togglePanel' }, (response) => {
    if (response) {
      panelVisible = response.panelVisible;
      const panel = document.getElementById('resource-extractor-panel');
      if (panel) {
        panel.style.display = panelVisible ? 'block' : 'none';
      }
    }
  });
}

// 处理右键菜单
function handleContextMenu(e) {
  const target = e.target;
  if (target.closest('.resource-item')) {
    e.preventDefault();
    const resourceItem = target.closest('.resource-item');
    const url = resourceItem.getAttribute('data-url');
    const type = resourceItem.getAttribute('data-type');
    const index = parseInt(resourceItem.getAttribute('data-index'));

    // 创建自定义右键菜单
    const menu = document.createElement('div');
    menu.className = 'custom-context-menu';
    menu.style.top = `${e.clientY}px`;
    menu.style.left = `${e.clientX}px`;

    // 添加下载选项
    const downloadOption = document.createElement('div');
    downloadOption.className = 'menu-option';
    downloadOption.textContent = '下载';
    downloadOption.addEventListener('click', () => {
      downloadResource(url, resources[type][index].filename);
      document.body.removeChild(menu);
    });

    // 添加下载所有选项
    const downloadAllOption = document.createElement('div');
    downloadAllOption.className = 'menu-option';
    downloadAllOption.textContent = `下载所有${type === 'images' ? '图片' : type === 'videos' ? '视频' : '音频'}`;
    downloadAllOption.addEventListener('click', () => {
      if (type === 'images') {
        downloadAllResources('images');
      } else if (type === 'videos') {
        downloadAllResources('videos');
      } else if (type === 'audios') {
        downloadAllResources('audios');
      }
      document.body.removeChild(menu);
    });

    // 组装菜单
    menu.appendChild(downloadOption);
    menu.appendChild(downloadAllOption);
    document.body.appendChild(menu);

    // 点击其他地方关闭菜单
    document.addEventListener('click', function closeMenu() {
      if (document.body.contains(menu)) {
        document.body.removeChild(menu);
      }
      document.removeEventListener('click', closeMenu);
    });
  }
}

// 下载资源
function downloadResource(url, filename) {
  chrome.runtime.sendMessage({
    action: 'downloadResource',
    url: url,
    filename: filename
  });
}

// 下载所有资源
function downloadAllResources(type) {
  resources[type].forEach(item => {
    downloadResource(item.url, item.filename);
  });
}

// 提取网页中的资源
function extractResources() {
  // 提取图片
  const images = Array.from(document.querySelectorAll('img')).map(img => {
    const url = img.src;
    if (!url || url.startsWith('data:') || !url.startsWith('http')) return null;
    
    const filename = url.split('/').pop().split('?')[0] || 'image.jpg';
    return {
      url: url,
      filename: filename,
      size: 0 // 实际大小需要通过请求获取
    };
  }).filter(Boolean);

  // 提取视频
  const videos = Array.from(document.querySelectorAll('video, source[type^="video"]')).map(video => {
    const url = video.src || video.currentSrc;
    if (!url || url.startsWith('data:') || !url.startsWith('http')) return null;
    
    const filename = url.split('/').pop().split('?')[0] || 'video.mp4';
    // 获取视频大小
    let size = 0;
    if (video instanceof HTMLVideoElement) {
      const duration = video.duration;
      // 估算文件大小：假设平均比特率为1Mbps
      if (!isNaN(duration)) {
        size = Math.round((duration * 1024 * 1024) / 8);
      }
    }

    // 尝试从video元素获取更准确的大小信息
    const sizeInfo = video.getAttribute('data-size') || 
                    video.closest('[data-size]')?.getAttribute('data-size');
    if (sizeInfo) {
      size = parseInt(sizeInfo, 10) || size;
    }

    return {
      url: url,
      filename: filename,
      size: size
    };
  }).filter(Boolean);

  // 提取音频
  const audioSelectors = [
    'audio',
    'source[type^="audio"]',
    // 通用音频选择器
    'audio[src], source[src]',
    '[data-audio-src], [data-src*=".mp3"]',
    '[data-url*=".mp3"], [data-media-url*=".mp3"]',
    // QQ音乐相关选择器
    '.player__music audio',
    '.player_music audio',
    '.player__bd audio',
    'audio[src*="qq.com"]',
    'audio[src*="qqmusic"]',
    // 网易云音乐相关选择器
    'audio[src*="music.126.net"]',
    'audio[src*="netease.com"]',
    // 通用音频播放器
    'audio[type^="audio"], source[type^="audio"]',
    '[data-role="audio-player"]',
    '[class*="audio-player"]',
    '[class*="player-container"] audio',
    // 自定义播放器
    '[data-type="audio"]',
    '[class*="music-player"]',
    '[id*="audio-player"]',
    // 嵌入式播放器
    'iframe[src*="music"]',
    'iframe[src*="audio"]'
  ];

  const audios = Array.from(document.querySelectorAll(audioSelectors.join(','))).map(audio => {
    // 尝试多种方式获取音频URL
    let url = audio.src || audio.currentSrc || audio.getAttribute('data-src') || audio.getAttribute('data-audio-src');
    
    // 检查各种可能的URL属性
    const urlAttributes = [
      'data-url', 'data-audio-url', 'data-media-url', 'data-source',
      'data-mp3', 'data-audio-source', 'data-music-url', 'href'
    ];
    
    if (!url) {
      for (const attr of urlAttributes) {
        url = audio.getAttribute(attr);
        if (url) break;
      }
    }
    
    // 检查父元素中的URL属性
    if (!url) {
      const container = audio.closest('[data-url], [data-audio-url], [data-media-url], [data-source], [data-mp3], [href*=".mp3"]');
      if (container) {
        for (const attr of urlAttributes) {
          url = container.getAttribute(attr);
          if (url) break;
        }
      }
    }
    
    // 检查相邻的<source>标签
    if (!url && audio.tagName === 'AUDIO') {
      const sources = audio.getElementsByTagName('source');
      for (const source of sources) {
        url = source.src || source.getAttribute('data-src');
        if (url) break;
      }
    }
    
    // 检查<a>标签中的音频链接
    if (!url) {
      const audioLink = audio.closest('a[href*=".mp3"], a[href*=".m4a"], a[href*=".wav"], a[href*=".ogg"]');
      if (audioLink) {
        url = audioLink.href;
      }
    }

    // 处理音乐平台的URL
    if (url) {
      // 处理QQ音乐加密URL
      if (url.includes('qq.com')) {
        const songMid = audio.getAttribute('data-songmid') || audio.getAttribute('data-mid');
        if (songMid) {
          url = `https://dl.stream.qqmusic.qq.com/${songMid}.m4a`;
        }
      }
      // 处理网易云音乐URL
      else if (url.includes('music.126.net') || url.includes('netease.com')) {
        // 保持原始URL，因为网易云音乐的URL已经包含了完整的音频地址
        // 但需要确保获取不带参数的基础URL
        url = url.split('?')[0];
      }
    }

    if (!url || url.startsWith('data:') || !url.startsWith('http')) return null;
    
    // 从URL或响应头中获取文件名和格式
    let filename = url.split('/').pop().split('?')[0];
    
    // 检查音频格式
    const audioFormats = ['mp3', 'm4a', 'wav', 'ogg', 'aac', 'flac', 'wma', 'opus', 'mid', 'midi'];
    let format = audioFormats.find(fmt => filename.toLowerCase().endsWith(fmt)) || 
                 audioFormats.find(fmt => url.toLowerCase().includes('.' + fmt)) || 'mp3';
    
    // 检查Content-Type
    if (audio instanceof HTMLAudioElement && audio.currentSrc) {
      try {
        const response = fetch(audio.currentSrc, { method: 'HEAD' });
        const contentType = response.headers.get('content-type');
        if (contentType) {
          const mimeToExt = {
            'audio/mpeg': 'mp3',
            'audio/mp4': 'm4a',
            'audio/wav': 'wav',
            'audio/ogg': 'ogg',
            'audio/aac': 'aac',
            'audio/flac': 'flac',
            'audio/x-ms-wma': 'wma',
            'audio/opus': 'opus',
            'audio/midi': 'mid'
          };
          format = mimeToExt[contentType] || format;
        }
      } catch (error) {
        console.debug('获取Content-Type失败:', error);
      }
    }
    
    // 音乐平台特殊处理
    if (url.includes('qq.com') || url.includes('music.126.net') || url.includes('netease.com')) {
      format = 'm4a';
      // 尝试从页面元素获取歌曲名称
      const songName = audio.getAttribute('data-songname') || 
                      audio.closest('[data-songname]')?.getAttribute('data-songname') ||
                      document.querySelector('.song_name')?.textContent ||
                      document.querySelector('.player__title')?.textContent ||
                      document.querySelector('.m-song-name')?.textContent;
      if (songName) {
        filename = `${songName.trim()}.${format}`;
      }
    }
    
    // 如果文件名不包含格式后缀，添加默认格式
    if (!audioFormats.some(fmt => filename.toLowerCase().endsWith(fmt))) {
      filename = `${filename}.${format}`;
    }
    
    // 清理文件名中的非法字符
    filename = filename.replace(/[<>:"/\\|?*]/g, '_');
    // 获取视频大小
    let size = 0;
    if (video instanceof HTMLVideoElement) {
      const duration = video.duration;
      // 估算文件大小：假设平均比特率为1Mbps
      if (!isNaN(duration)) {
        size = Math.round((duration * 1024 * 1024) / 8);
      }
    }

    // 尝试从video元素获取更准确的大小信息
    const sizeInfo = video.getAttribute('data-size') || 
                    video.closest('[data-size]')?.getAttribute('data-size');
    if (sizeInfo) {
      size = parseInt(sizeInfo, 10) || size;
    }

    return {
      url: url,
      filename: filename,
      size: size
    };
  }).filter(Boolean);

  // 更新资源列表
  resources = {
    images: [...new Map(images.map(item => [item.url, item])).values()],
    videos: [...new Map(videos.map(item => [item.url, item])).values()],
    audios: [...new Map(audios.map(item => [item.url, item])).values()]
  };

  // 更新资源大小
  updateResourceSizes();

  // 更新后台存储
  chrome.runtime.sendMessage({
    action: 'updateResources',
    resources: resources
  });

  // 更新面板
  updatePanel();
}

// 更新资源大小
function updateResourceSizes() {
  // 更新图片大小
  resources.images.forEach((image, index) => {
    getResourceSize(image.url).then(size => {
      if (size) {
        resources.images[index].size = size;
        updateResourceItem('images', index);
      }
    });
  });

  // 更新视频大小
  resources.videos.forEach((video, index) => {
    getResourceSize(video.url).then(size => {
      if (size) {
        resources.videos[index].size = size;
        updateResourceItem('videos', index);
      }
    });
  });

  // 更新音频大小
  resources.audios.forEach((audio, index) => {
    getResourceSize(audio.url).then(size => {
      if (size) {
        resources.audios[index].size = size;
        updateResourceItem('audios', index);
      }
    });
  });
}

// 获取资源大小的通用函数
async function getResourceSize(url) {
  // 首先尝试使用HEAD请求
  try {
    const response = await fetch(url, { method: 'HEAD' });
    const size = response.headers.get('content-length');
    if (size) {
      return parseInt(size);
    }
  } catch (error) {
    console.debug('HEAD请求获取资源大小失败:', error);
  }

  // 如果HEAD请求失败，尝试使用XHR请求
  try {
    return await new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      xhr.open('GET', url, true);
      xhr.responseType = 'arraybuffer';

      // 设置请求头，尝试获取更多信息
      xhr.setRequestHeader('Range', 'bytes=0-1'); // 只请求前两个字节
      xhr.setRequestHeader('Accept-Ranges', 'bytes');

      xhr.onload = function() {
        if (xhr.status === 200 || xhr.status === 206) {
          // 从Content-Range头获取文件大小
          const range = xhr.getResponseHeader('Content-Range');
          if (range) {
            const size = range.split('/')[1];
            if (size && !isNaN(size)) {
              resolve(parseInt(size));
              return;
            }
          }
          // 如果没有Content-Range头，使用响应大小
          resolve(xhr.response.byteLength);
        } else {
          reject(new Error('XHR请求失败'));
        }
      };

      xhr.onerror = function() {
        reject(new Error('XHR请求错误'));
      };

      // 添加进度事件以支持取消大文件下载
      xhr.onprogress = function(event) {
        if (event.lengthComputable && event.total > 0) {
          resolve(event.total);
          xhr.abort(); // 一旦获得文件大小就取消下载
        }
      };

      xhr.send(null);

      // 设置超时以避免长时间等待
      setTimeout(() => {
        xhr.abort();
        reject(new Error('请求超时'));
      }, 10000);
    });
  } catch (error) {
    console.debug('XHR请求获取资源大小失败:', error);
    return 0; // 如果所有方法都失败，返回0
  }
}

// 更新资源项
function updateResourceItem(type, index) {
  const panel = document.getElementById('resource-extractor-panel');
  if (!panel) return;

  const resourceItem = panel.querySelector(`#${type}-tab .resource-item[data-index="${index}"]`);
  if (resourceItem) {
    const sizeElement = resourceItem.querySelector('.resource-size');
    if (sizeElement) {
      sizeElement.textContent = formatSize(resources[type][index].size);
    }
  }
}

// 更新面板
function updatePanel() {
  const panel = document.getElementById('resource-extractor-panel');
  if (!panel) return;

  // 更新标签页计数
  const imageBadge = panel.querySelector('.tab-btn[data-tab="images"]');
  const videoBadge = panel.querySelector('.tab-btn[data-tab="videos"]');
  const audioBadge = panel.querySelector('.tab-btn[data-tab="audios"]');

  if (imageBadge) imageBadge.textContent = `图片 (${resources.images.length})`;
  if (videoBadge) videoBadge.textContent = `视频 (${resources.videos.length})`;
  if (audioBadge) audioBadge.textContent = `音频 (${resources.audios.length})`;

  // 更新资源列表
  const imagesTab = panel.querySelector('#images-tab');
  const videosTab = panel.querySelector('#videos-tab');
  const audiosTab = panel.querySelector('#audios-tab');

  if (imagesTab) {
    imagesTab.innerHTML = '';
    imagesTab.appendChild(createResourceList('images', resources.images));
  }

  if (videosTab) {
    videosTab.innerHTML = '';
    videosTab.appendChild(createResourceList('videos', resources.videos));
  }

  if (audiosTab) {
    audiosTab.innerHTML = '';
    audiosTab.appendChild(createResourceList('audios', resources.audios));
  }
}

// 监听来自后台的消息
let messageListener = null;

// 设置消息监听器
function setupMessageListener() {
  if (messageListener) {
    try {
      chrome.runtime.onMessage.removeListener(messageListener);
    } catch (error) {
      console.debug('移除旧的消息监听器时出错:', error);
    }
  }

  messageListener = (request, sender, sendResponse) => {
    try {
      if (request.action === 'downloadAll') {
        downloadAllResources('images');
        downloadAllResources('videos');
        downloadAllResources('audios');
      } else if (request.action === 'downloadImages') {
        downloadAllResources('images');
      } else if (request.action === 'downloadVideos') {
        downloadAllResources('videos');
      } else if (request.action === 'downloadAudios') {
        downloadAllResources('audios');
      }
    } catch (error) {
      console.debug('处理消息时出错:', error);
      if (error.message.includes('Extension context invalidated')) {
        // 重新初始化
        setTimeout(initialize, 1000);
      }
    }
  };

  try {
    chrome.runtime.onMessage.addListener(messageListener);
  } catch (error) {
    console.debug('添加消息监听器时出错:', error);
  }
}

// 初始化
function initialize() {
  try {
    // 设置消息监听器
    setupMessageListener();
    
    // 从存储中获取面板状态
    chrome.runtime.sendMessage({ action: 'getResources' }, (response) => {
      if (chrome.runtime.lastError) {
        console.debug('获取资源时出错:', chrome.runtime.lastError);
        return;
      }
      
      if (response) {
        resources = response;
      }
      
      try {
        // 提取资源
        extractResources();
        
        // 创建面板
        createResourcePanel();
        
        // 设置定期更新
        const updateInterval = setInterval(() => {
          try {
            extractResources();
          } catch (error) {
            console.debug('资源提取时出错:', error);
            if (error.message.includes('Extension context invalidated')) {
              clearInterval(updateInterval);
              setTimeout(initialize, 1000);
            }
          }
        }, 5000);
        
        // 清理函数
        window.addEventListener('unload', () => {
          clearInterval(updateInterval);
        });
      } catch (error) {
        console.debug('初始化过程出错:', error);
      }
    });
  } catch (error) {
    console.debug('初始化函数出错:', error);
    if (error.message.includes('Extension context invalidated')) {
      setTimeout(initialize, 1000);
    }
  }
}

// 页面加载完成后初始化
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', initialize);
} else {
  initialize();
}